<?php

/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/10/11
 * Time: 17:05
 */

namespace app\api\controller;

use app\api\Base2Controller;
use app\common\model\QuestionOption;
use app\common\model\Equipment as EquipmentModel;
use app\common\model\Refundreturn;

/**
 * @title 服务端
 */
class Service extends Base2Controller
{
    /**
     * @title 服务端---订单列表
     * @description
     * @param string order_sn 订单编号(搜索)
     * @param string query_start_date 开始时间(搜索)
     * @param string query_end_date 结束时间(搜索)
     * @param string state_type 订单状态
     * @return {"code":200,"msg":"succeess"}
     * @author zjw
     * @url /Service/select
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败service_over_sorder
     * 0：待接单   （总后台派单之后）
     * 1：已接单   （点完接单按钮，出发）服务人员点出发之后，修改客户端的服务单已出发状态
     * 2：已完成   （服务完成）
     */
    public function select()
    {
        $status = intval(input('param.status'));   // 0--待接单 1--已接单 2--已完成
        $order_sn = input('param.order_sn');  #订单编号
        $order_type = input('param.order_type');  #订单类型
        $appointment_time = input('param.appointment_time');

        //筛选条件 
        $parms['merid'] = $this->user_id;
        $parms['service_type'] = 0; #主单

        //判断状态
        switch ($status) {
            case 0:
                $parms['status'] = 0;
                $params['order_state'] = 8;  #主单状态
                break;
            case 1:
                $parms['status'] = 1;
                $params['order_state'] = 7;  #主单状态
                break;
            case 2:
                $parms['status'] = array('in', '3,4,6');
                $params['service_state'] = 4;  #主单状态
                break;
            default:
                break;
        }
        if (!empty($order_sn)) {
            $parms['order_sn'] = array('like', '%' . $order_sn . '%');
        }

        if (!empty($order_type)) {
            $parms['order_type'] = $order_type;
        }

        $query_start_date = input('param.query_start_date');
        $query_end_date = input('param.query_end_date');

        if ($query_start_date || $query_end_date) {
            $parms['appointment_unix_time'] = array('between', array($query_start_date, $query_end_date));
        }

        $page = intval(input('page')) ? intval(input('page')) : 1;
        $pagesize = intval(input('pagesize')) ? intval(input('pagesize')) : 15;
        $offset = ($page - 1) * $pagesize;

        $service_list = db('s_order_mechanic')->alias('som')
            ->join('s_order so', 'so.order_id = som.order_id')
            ->join('address a', 'a.address_id = so.address_id')
            ->limit($offset, $pagesize)
            ->where($parms)
            ->select();
        //获取信息
        foreach ($service_list as $key => $value) {
            //获取文字
            $service_list[$key]['order_type_text'] = getSorderText($value['order_type']);

            //获取当前订单下面的设备
            $equipment_list = db('s_order_detail')->where(['order_id' => $value['order_id']])->select();

            foreach ($equipment_list as $k => $v) {
                $item = [
                    'goods_name' => $v['goods_name'],
                    'b_name' => $v['b_name'],
                    'type_model' => $v['type_model']
                ];
                $service_list[$key]['equipment_list'][$k] = array_merge($service_list[$key], $item);
            }

            #如果是被更换下来的，合计金额为补贴金额
            if ($value['status'] == 6) {
                $service_list[$key]['assign_mechanic_total'] = $value['money'];
            }
        }
        json_success_return($service_list);
    }

    /**
     * @title 服务端---服务订单详情
     * @description
     * @param string order_id 订单id
     * @return {"code":200,"msg":"succeess"}
     * @author zjw
     * @url /Service/detail
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function detail()
    {

        $order_id = intval(input('param.order_id'));

        if ($order_id <= 0) {
            return json_fail_return('该订单不存在');
        }

        //1、获取主单详情
        $s_order_list['order_list'] = db('s_order')->where('order_id', $order_id)->find();
        $s_order_list['order_list']['order_type_text'] = getSorderText($s_order_list['order_list']['order_type']);
        $s_order_list['order_list']['add_time'] = date('Y-m-d H:i', $s_order_list['order_list']['add_time']);

        #获取预约人姓名
        $member_info = db('address')->where(['address_id' => $s_order_list['order_list']['address_id']])->find();
        $member_name = empty($member_info['address_realname']) ? '未设置' : $member_info['address_realname'];
        $s_order_list['order_list']['member_name'] = $member_name;

        #获取经纬度
        $address_info = db('address')->where(['address_id' => $s_order_list['order_list']['address_id']])->find();
        $s_order_list['order_list']['address_longitude'] = $address_info['address_longitude'];
        $s_order_list['order_list']['address_latitude'] = $address_info['address_latitude'];

        #获取拒单详情
        $refuse_info = db('s_order_mechanic')->where(['order_id' => $order_id, 'merid' => $this->user_id])->find();
        $s_order_list['order_list']['refuse_status'] = $refuse_info['status'];
        $s_order_list['order_list']['money'] = $refuse_info['money']; #补贴金额

        #如果是更换下来的，上门费为0
        if ($refuse_info['status'] == 6) {
            $s_order_list['order_list']['assign_mechanic_total'] = $refuse_info['money'];
            $s_order_list['order_list']['door_fee'] = 0.00;
        }

        // p($s_order_list);die;
        if (empty($s_order_list)) {
            json_fail_return('订单id信息错误');
        }

        # 获取主单下面的所有设备
        $zhu_goods_list = db('s_order_detail')->where('order_id', $order_id)->select();

        foreach ($zhu_goods_list as $key => $value) {
            $s_order_list['order_list']['goods_list'][$key]['goods_name'] = $value['goods_name'];
            $s_order_list['order_list']['goods_list'][$key]['b_name'] = $value['b_name'];
            $s_order_list['order_list']['goods_list'][$key]['type_model'] = $value['type_model'];
        }
        $s_order_list['order_list']['count_hours'] = $s_order_list['order_list']['work_master_hous'];

        //2、获取追加单下面的所有设备
        $append_order_list = db('s_order')->where(['parent_id' => $order_id])->select();

        # 获取追加订单下面所有的设备
        $s_order_list['order_list']['append_goods_list'] = [];

        foreach ($append_order_list as $key => $value) {
            #获取追加订单设备详情
            $append_hour_price = 0; #追加单的给服务人员的总工时费
            $append_part_price = 0; #追加单的配件总金额

            $append_goods_list = db('s_order_detail')->where('order_id', $value['order_id'])->select();
            foreach ($append_goods_list as $k => $v) {
                $append_hour_price += ($v['fuwu_hour'] * $v['need_hours']);
                $part_info = db('s_order_parts')->where(['detail_order_id'=>$v['id']])->select();
                foreach($part_info as $vv){
                    $append_part_price += ($vv['num'] * $vv['part_price']);
                }
                $item = [
                    'son_order_id' => $value['order_id'],
                    #给服务人员展示的总价，只是服务人员该看到的金额 （追加单的上门费，追加单的给服务人员的总工时费，追加单的配件总金额）
                    'order_amount' => $value['door_fee'] + $append_hour_price + $append_part_price,  
                    'order_state' => $value['order_state'],
                    'order_text' => getSorderStatus($value['order_state']),
                    'goods_name' => $v['goods_name'],
                    'b_name' => $v['b_name'],
                    'type_model' => $v['type_model'],
                    'examine_failed_reason' => $value['examine_failed_reason']
                ];
                array_push($s_order_list['order_list']['append_goods_list'], $item);
            }
        }

        //3、获取追加工时的所有信息
        $s_order_list['order_list']['append_order_hours'] = [];
        $append_order_hours = db('s_order_append')->where(['order_id' => $order_id])->select();
        foreach ($append_order_hours as $key => $value) {
            //获取服务人员信息
            $originator_info = db('fuwu_personal')->where(['id' => $value['originator']])->find();

            $s_order_list['order_list']['append_order_hours'][$key]['originator'] = $originator_info['name'];
            #判断是前台追加还是后台追加
            if ($value['originator'] == 0) {
                $s_order_list['order_list']['append_order_hours'][$key]['originator'] = '管理员';
            }

            $s_order_list['order_list']['append_order_hours'][$key]['add_hours'] = $value['add_hours'];
            $s_order_list['order_list']['append_order_hours'][$key]['created_at'] = date('Y-m-d H:i:s', $value['created_at']);

            $s_order_list['order_list']['append_order_hours'][$key]['fail_reason'] = $value['fail_reason'];
            #支付状态
            $s_order_list['order_list']['append_order_hours'][$key]['status'] = $value['status'];
            #审核状态
            $s_order_list['order_list']['append_order_hours'][$key]['audit_status'] = $value['audit_status'];
            $s_order_list['order_list']['append_order_hours'][$key]['hours_price'] = number_format($value['payper_hour'] * $value['add_hours'], 2);
        }

        //4、获取更换人员记录
        $s_order_list['order_list']['change_personal'] = [];
        $change_order_personal = db('s_order_change')->where(['order_id' => $order_id])->select();
        foreach ($change_order_personal as $key => $value) {
            $s_order_list['order_list']['change_personal'][$key]['refusal_reason'] = $value['refusal_reason'];
            $s_order_list['order_list']['change_personal'][$key]['c_time'] = date('Y-m-d H:i:s', $value['c_time']);
            $s_order_list['order_list']['change_personal'][$key]['refusal_remake'] = $value['refusal_remake'];
            $s_order_list['order_list']['change_personal'][$key]['fail_reason'] = $value['fail_reason'];
            #审核状态
            $s_order_list['order_list']['change_personal'][$key]['status'] = $value['status'];
        }

        json_success_return($s_order_list);
    }


    //获取子订单详情  
    public function son_detail()
    {
        $data = input('post.');

        if (empty($data['type'])) {
            json_fail_return('参数错误');
        }

        //根据type来区分是主订单详情 还是 追加订单详情
        $param = [];

        if ($data['type'] == 1) {
            $param['order_id'] = $data['order_id'];  #主订单

            #获取主单下面的所有设备
            $son_goods_info = db('s_order_detail')->where('order_id', $data['order_id'])->select();

            $s_order_list = [];
            foreach ($son_goods_info as $key => $value) {
                //1、获取设备信息
                $s_order_list[$key]['goods_info'] = $value;

                //2、获取每个商品需要的配件
                $parts_list = db('s_order_parts')->where(['detail_order_id' => $value['id']])->select();
                $s_order_list[$key]['part_list'] = [];
                $parts_total = 0; #配件总价
                foreach ($parts_list as $k => $v) {
                    #单个配件的信息
                    $good_info = db('goods')->alias('g')
                        ->join('goodscommon gc', 'gc.goods_commonid = g.goods_commonid')
                        ->where(['goods_id' => $v['good_id']])
                        ->find();
                    #配件名称
                    $s_order_list[$key]['part_list'][$k]['part_name'] = $good_info['goods_name'] . ' ' . $good_info['spec_values'];
                    #配件品牌
                    $s_order_list[$key]['part_list'][$k]['brand_name'] = $good_info['brand_name'];
                    // #配件规格型号
                    // $s_order_list[$key]['part_list'][$k]['spec_values'] = $good_info['spec_values'];
                    #配件单价
                    $s_order_list[$key]['part_list'][$k]['technician_price'] = $v['part_price'];
                    #配件数量
                    $s_order_list[$key]['part_list'][$k]['part_num'] = $v['num'];
                    #是否带货 0--不需要 1--需要
                    $s_order_list[$key]['part_list'][$k]['is_bring_goods'] = $v['is_bring_goods'];
                    #配件总价
                    $parts_total += $v['num'] * $v['part_price'];
                }
                $s_order_list[$key]['parts_total'] = number_format($parts_total, 2);

                //3、获取图片
                $s_order_list[$key]['img_list'] = db('s_order_image')->where(['order_detail_id' => $value['id']])->select();
                foreach ($s_order_list[$key]['img_list'] as $k => $v) {
                    $s_order_list[$key]['img_list'][$k]['src'] = $v['src'];
                }

                //4、获取环境配置
                $s_order_list[$key]['science_list'] = [];
                if (!empty($value['scienceIds'])) {
                    $scienceIds_array = explode(',', $value['scienceIds']);
                    foreach ($scienceIds_array as $k => $v) {
                        $s_order_list[$key]['science_list'][$k] = db('equipment_science')->where(['id' => $v])->find();
                    }
                }
                //5、获取部位
                $s_order_list[$key]['option_list'] = [];
                if (!empty($value['option_info'])) {
                    $option_list = json_decode($value['option_info'], true);
                    foreach ($option_list as $k => $v) {
                        $s_order_list[$key]['option_list'][] = db('equipment_option')->where(['id' => $v['oid']])->find();
                        $s_order_list[$key]['option_list'][$k]['selected'] = $v['selected'];
                    }
                }
            }
        } else {
            $param['parent_id'] = $data['order_id']; #追加订单

            #获取所有追加的订单信息
            $append_order_list = db('s_order')->where($param)->select();

            $equipment_list = []; #返回返回设备
            #遍历所有追加订单，获取每个订单下的所有设备
            foreach ($append_order_list as $key => $value) {

                #根据追加订单的订单id获取所有设备详情
                $append_goods_list = db('s_order_detail')->where('order_id', $value['order_id'])->select();

                foreach ($append_goods_list as $k => $v) {
                    $equipment_item = [];
                    $v['append_door_fee'] = $value['door_fee']; #追加单上门费
                    //1、获取每个设备的详情
                    $equipment_item['goods_info'] = $v;

                    //2、获取每个商品需要的配件
                    $parts_list = db('s_order_parts')->where(['detail_order_id' => $v['id']])->select();
                    $parts_total = 0; #配件总价
                    $parts_list_append = [];
                    foreach ($parts_list as $k => $parts) {
                        #单个配件的信息
                        $good_info = db('goods')->alias('g')
                            ->join('goodscommon gc', 'gc.goods_commonid = g.goods_commonid')
                            ->where(['goods_id' => $parts['good_id']])
                            ->find();

                        $parts_list_append[] = [
                            'part_name' => $good_info['goods_name'],
                            'brand_name' => $good_info['brand_name'],
                            'technician_price' => $parts['part_price'],
                            'part_num' => $parts['num'],
                            'is_bring_goods' => $parts['is_bring_goods']
                        ];
                        $parts_total  += $parts['num'] * $parts['part_price'];
                    }
                    $equipment_item['part_list'] = $parts_list_append; //配件列表
                    $equipment_item['parts_total'] = $parts_total; //配件总价

                    //3、获取图片
                    $s_order_list[$key]['img_list'] = db('s_order_image')->where(['order_detail_id' => $v['id']])->select();
                    $image_list = [];
                    foreach ($s_order_list[$key]['img_list'] as $k => $img) {
                        $image_list[] = [
                            'id' => $img['id'],
                            'order_detail_id' => $v['id'],
                            'src' => $img['src']
                        ];
                    }
                    $equipment_item['img_list'] = $image_list;

                    //4、获取环境配置
                    $scene_list = [];
                    if (!empty($v['scienceIds'])) {
                        $scienceIds_array = explode(',', $v['scienceIds']);
                        foreach ($scienceIds_array as $kk => $science) {
                            $scene_list[] = db('equipment_science')->where(['id' => $science])->find();
                        }
                    }
                    $equipment_item['science_list'] = $scene_list;

                    //5、获取部位
                    $position_list = [];
                    if (!empty($v['option_info'])) {
                        $option_list = json_decode($v['option_info'], true);
                        foreach ($option_list as $kkk => $option) {
                            $position_list[] =  db('equipment_option')->where(['id' => $option['oid']])->find();
                            $position_list[count($position_list) - 1]['selected'] = $option['selected'];
                        }
                    }
                    $equipment_item['option_list'] = $position_list;
                    $equipment_list[] = $equipment_item;
                }
            }
            $s_order_list = $equipment_list;
        }
        json_success_return($s_order_list);
    }

    /**
     * @title 服务端 服务人员选择配件
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Equipment/get_refusal_reason
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_choice_parts()
    {
        $order_id = intval(input('post.order_id'));
        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }
        #商品订单详情
        $order_detail_info = db('s_order_detail')->where(['order_id' => $order_id])->select();

        $parts_lists = [];
        foreach ($order_detail_info as $key => $value) {
            #找个当前商品下面的所有配件
            $parts_list = db('s_order_parts')->where(['detail_order_id' => $value['id'], 'type' => 1])->select();
            foreach ($parts_list as $k => $v) {
                #找到商品
                $goods_info = db('goods')->alias('g')
                    ->join('brand b', 'b.brand_id = g.brand_id')
                    ->where(['g.goods_id' => $v['good_id']])
                    ->field('g.goods_name,g.brand_id,g.spec_values,g.goods_id,g.technician_price,b.brand_name')
                    ->find();
                $goods_common_info = db('goodscommon')->where(['goods_commonid' => $v['goods_commonid']])->find();
                $goods_info['goods_name'] = $goods_common_info['goods_name'];
                $goods_info['goods_num'] = $v['num'];
                $goods_info['parts_id'] = $v['id'];
                $goods_info['parts_price'] = $v['part_price'];
                $parts_lists['parts_list'][] = $goods_info;
            }
        }

        return json_success_return($parts_lists);
    }

    /**
     * @title 服务端---服务人员接单
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Service/service_receie_sorder
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function service_receie_sorder()
    {
        $order_id = intval(input('param.order_id'));
        $parts_ids = input('param.parts_id'); #服务人员选择的配件id

        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }
        

        //获取订单指派表详情
        $receie_info = db('s_order_mechanic')->where(['order_id' => $order_id])->find();

        if ($receie_info['status'] == 1) {
            return json_fail_return('当前订单正在进行中');
        }

        //修改订单指派表状态  如果派给多人，当前服务人员的id为已接单，其他人员为拒单
        $mechanic_list = db('s_order_mechanic')->where(['order_id' => $order_id,'status'=>0])->select();

        foreach ($mechanic_list as $key => $value) {
            if ($value['merid'] == $this->user_id) {
                db('s_order_mechanic')->where(['id' => $value['id']])->update(['status' => 1, 'update_at' => time()]);
            } else {
                $where['merid'] = array('neq', $this->user_id);
                $where['order_id'] = $order_id;
                db('s_order_mechanic')->where($where)->update(['status' => 2, 'update_at' => time()]);
            }
        }

        //获取服务人员信息
        $mechanic_info = db('fuwu_personal')->where(['id' => $this->user_id])->find();

        //修改订单详情表里面的预约人信息
        $order_detail_list = db('s_order_detail')->where(['order_id' => $order_id])->select();

        foreach ($order_detail_list as $key => $value) {
            db('s_order_detail')->where(['order_id' => $order_id])->update(['mechanic_id' => $this->user_id, 'mechanic_name' => $mechanic_info['name']]);
        }

        //计算服务人员选择配件的配件总金额
        $service_part_price = 0; #配件金额
        if ($parts_ids) {
            $part_ids = explode(',', $parts_ids);
            foreach ($part_ids as $k => $v) {
                db('s_order_parts')->where(['id' => $v])->update(['is_bring_goods' => 1]);
                $part_info = db('s_order_parts')->where(['id' => $v])->find();
                $service_part_price += ($part_info['num'] * $part_info['part_price']);
            }
        }
        $s_order_info = db('s_order')->where(['order_id' => $order_id])->find();
        $update_data = [
            'service_state' => 1,
            'order_state' => 7,
            'assign_mechanic_id' => $mechanic_info['id'],
            'assign_mechanic_name' => $mechanic_info['name'],
            'service_part_price' => $service_part_price,
            'receiving_time' => time(),
            'assign_mechanic_total' => $s_order_info['assign_mechanic_total'] + $service_part_price #选择完配件之后，服务人员的总金额
        ];

        //生成商品单，服务人员不带的配件生成商品单
        $equipmentModel = new EquipmentModel();
        $equipmentModel->getGenerateSorder($order_id, $parts_ids);

        //修改主单的服务人员状态  
        db('s_order')->where(['order_id' => $order_id])->update($update_data);

        //修改服务人员价格
        $mechanic_info = db('s_order_mechanic')->where(['order_id' => $order_id])->select();
        foreach ($mechanic_info as $k => $v) {
            $service_money = $v['service_money'] + $service_part_price;
            db('s_order_mechanic')->where(['id' => $v['id']])->update(['service_money' => $service_money]);
        }
        #推送
        $order_info = db('s_order')->where(['order_id' => $order_id])->find();
        $member_info = db('member')
            ->where(['member_id' => $order_info['member_id']])
            ->find();
        #通知内容
        $notif_data = [
            'order_id' =>  $order_id,
            'notif_title' => '接单通知',
            'notif_content' =>  '您提交的服务单已接单，请及时查看！',
            'member_id' => $order_info['member_id'],
            'member_name' => $order_info['member_name'],
        ];
        model('points')->saveAfficeslog(2, 0, $notif_data); #客户    
        pushMessageToSingle('接单通知', $member_info['clientid'], '您提交的服务单已接单，请及时查看！');

        #服务单订单日志
        $data = array();
        $data['order_id'] = $order_id;
        $data['log_msg'] = '服务人员已接单';
        $data['log_time'] = time();
        $data['log_role'] = 'service';
        $data['log_user'] = $this->user_id;
        $data['log_orderstate'] = 4;
        $data['log_singlestate'] = 1;
        model('order')->addSorderlog($data);

        
        $fuwu_info = db('fuwu_personal')->where(['id' => $this->user_id])->find();
        if($fuwu_info['receiv_num'] == 0 && $fuwu_info['prevtype'] == 4){ #服务人员邀请服务人员
            #通过上级邀请人的id， 送余额
            $superior_info = db('fuwu_personal')->where(['id'=>$fuwu_info['prev']])->find();

            //增加余额
            $config = db('config')->where('code', 'service_invitation')->find();

            $receiv_num = $fuwu_info['receiv_num'] + 1; #接单次数
            db('fuwu_personal')->where(['id'=>$this->user_id])->update(['receiv_num'=>$receiv_num]);

            $points = $superior_info['money'] + $config['value'];
            db('fuwu_personal')->where(['id'=>$fuwu_info['prev']])->update(['money'=>$points]);

             #日志
             $log_data = [
                'member_id' => $superior_info['id'],
                'type' => 1,
                'name' => $superior_info['phone'],
                'money' => $config['value'],
                'surplus_money' => $points,
                'money_type' => 2,
                'addtime' => time(),
                'desc' => '邀请新服务人员[' . $fuwu_info['phone'] . ']注册',
            ];
            db('money_log')->insertGetId($log_data);
        }

        return json_success_return([], '您已接单');
    }

    /**
     * @title 服务端 拒单原因
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Equipment/get_refusal_reason
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_refuse_reason()
    {
        $RefundreturnModel = new Refundreturn();
        $type = intval(input('post.type'));
        if (empty($type)) {
            return json_fail_return('参数错误');
        }
        $result = $RefundreturnModel->getRefusalReason($type);
        return json_success_return($result);
    }


    /**
     * @title 服务端---服务人员拒单
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Service/service_receie_sorder
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function service_refuse_sorder()
    {
        $data = input('post.');

        $order_id = intval(input('param.order_id'));

        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }
        if (empty($data['refuse_remark'])) {
            return json_fail_return('请输入拒单说明');
        }

        //获取订单指派表详情
        $mechanic_list = db('s_order_mechanic')->where(['order_id' => $order_id])->select();

        if (empty($mechanic_list)) {
            return json_fail_return('操作失败');
        }

        #修改指派表的接单状态
        db('s_order_mechanic')->where(['order_id' => $order_id, 'merid' => $this->user_id])->update(['status' => 2, 'refuse_reason' => $data['refuse_reason'], 'refuse_remark' => $data['refuse_remark']]);

        #遍历查看是否所有人都已经拒单,
        $order_num = count($mechanic_list);
        $i = 0; #统计拒单的数量

        $new_mechanic_list = db('s_order_mechanic')->where(['order_id' => $order_id])->select();
        foreach ($new_mechanic_list as $key => $value) {
            if ($value['status'] == 2) {
                $i++;
            }
        }

        #所有人都拒单，改变主单状态,重新派单
        if ($order_num == $i) {
            #判断派单的次数，如果是派单2次之后将这个订单改为疑难单。
            $order_info = db('s_order')->where(['order_id' => $order_id])->find();

            $order_data = [
                'order_state' => 3,
                'service_state' => 0,
            ];

            if ($order_info['distribute_nums'] == 2) {
                #疑难单
                $order_data['is_doubt_order'] = 1;
            }

            db('s_order')->where(['order_id' => $order_id])->update($order_data);
        }

        #服务单订单日志
        $data = array();
        $data['order_id'] = $order_id;
        $data['log_msg'] = '服务人员已拒单';
        $data['log_time'] = time();
        $data['log_role'] = 'service';
        $data['log_user'] = $this->user_id;
        $data['log_orderstate'] = 4;
        $data['log_singlestate'] = 1;
        model('order')->addSorderlog($data);

        return json_success_return([], '操作成功');
    }

    /**
     * @title 服务端---服务人员出发、到达
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Service/service_receie_sorder
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function service_change_status()
    {
        $order_id = intval(input('param.order_id'));
        $operation_type = intval(input('param.operation_type')); # 1--出发 2--到达

        $order_info = db('s_order')->where(['order_id' => $order_id])->find();

        $member_info = db('member')
            ->where(['member_id' => $order_info['member_id']])
            ->find();

        if (empty($order_id) || empty($operation_type)) {
            return json_fail_return('参数错误');
        }

        if ($operation_type == 1) {
            $updata_data['service_state'] = 2;
            $data['log_msg'] = '服务人员已出发';
            #推送
            pushMessageToSingle('服务单通知', $member_info['clientid'], '服务人员已出发，请等待服务人员上门服务！');
            $msg = '您已出发';
        } else {
            $updata_data['service_state'] = 3;
            $data['log_msg'] = '服务人员已到达';
            pushMessageToSingle('服务单通知', $member_info['clientid'], '服务人员已到达，请等待服务人员上门服务！');
            $msg = '您已到达';
        }

        $notif_data = [
            'order_id' =>  $order_id,
            'notif_title' => '服务单通知',
            'notif_content' =>  $data['log_msg'] . '，请等待服务人员上门服务！',
            'member_id' => $order_info['member_id'],
            'member_name' => $order_info['member_name'],
        ];
        model('points')->saveAfficeslog(2, 0, $notif_data); #客户   

        //修改主单的服务人员状态 
        db('s_order')->where(['order_id' => $order_id])->update($updata_data);

        #服务单订单日志
        $data = array();
        $data['order_id'] = $order_id;
        $data['log_time'] = time();
        $data['log_role'] = 'service';
        $data['log_user'] = $this->user_id;
        $data['log_orderstate'] = 3;

        model('order')->addSorderlog($data);

        return json_success_return([], $msg);
    }

    /**
     * @title 服务端---服务人员服务完成
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Service/service_over_sorder
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function service_over_sorder()
    {
        $order_id = intval(input('param.order_id'));
        $autograph = input('param.autograph');  #服务人员签名
        $imgs = input('param.imgs');  #现场图片 多图

        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }
        if (empty($autograph)) {
            return json_fail_return('请上传服务人员签名');
        }
        if (empty($imgs)) {
            return json_fail_return('请上传现场图片');
        }
        #判断是否有追加工时
        $order_append = db('s_order_append')->where(['order_id' => $order_id])->select();
        if ($order_append) {
            foreach ($order_append as $key => $value) {
                if ($value['audit_status'] == 0) {
                    return json_fail_return('当前有追加服务单审核中，暂不能服务完成。');
                }else if ($value['status'] == 1) {
                    return json_fail_return('当前有追加服务单未支付，暂不能服务完成。');
                } 
            }
        }
        //判断是否有追加设备
        $append_service = db('s_order')->where(['parent_id' => $order_id])->select();
        if ($append_service) {
            foreach ($append_service as $key => $value) {
                if ($value['order_state'] == 1) {
                    return json_fail_return('当前有追加服务单审核中，暂不能服务完成。');
                }  else if ($value['order_state'] == 2) {
                    return json_fail_return('当前有追加服务单未支付，暂不能服务完成。');
                }
            }
        }



        //修改订单指派表状态
        db('s_order_mechanic')->where(['merid' => $this->user_id, 'order_id' => $order_id])->update(['status' => 3, 'update_at' => time()]);

        //修改主单的服务人员状态 
        db('s_order')->where(['order_id' => $order_id])->update(['service_state' => 4, 'mechanics_confirm_time' => time(), 'service_autograph' => $autograph, 'imgs' => $imgs]);

        $order_info = db('s_order')->find($order_id);
        $member_info = db('member')->find($order_info['member_id']);
        $notif_data = [
            'order_id' =>  $order_id,
            'notif_title' => '服务单通知',
            'notif_content' => '当前服务已完成，请及时验收！',
            'member_id' => $member_info['member_id'],
            'member_name' => $member_info['member_name'],
        ];
        model('points')->saveAfficeslog(2, 0, $notif_data); #客户   
        pushMessageToSingle('服务单通知', $member_info['clientid'], '当前服务已完成，请及时验收！');
        #服务单订单日志
        $data = array();
        $data['order_id'] = $order_id;
        $data['log_msg'] = '服务人员服务完成';
        $data['log_time'] = time();
        $data['log_role'] = 'service';
        $data['log_user'] = $this->user_id;
        $data['log_orderstate'] = 4;

        model('order')->addSorderlog($data);
        return json_success_return([], '该订单已服务完成');
    }

    /**
     * @title 服务端---服务人员追加服务
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Service/service_append_sorder
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function service_append_sorder()
    {
        $order_id = intval(input('param.order_id'));
        $add_hours = input('param.add_hours');  #要加的工时
        $add_remarks = input('param.add_remarks');  #追加说明
        $additional_reasons_name = input('param.additional_reasons_name');  #追加原因

        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }
        if (empty($additional_reasons_name)) {
            return json_fail_return('请选择追加原因');
        }
        if (empty($add_remarks)) {
            return json_fail_return('请输入追加说明');
        }

        $personal_info = db('fuwu_personal')->where(['id' => $this->user_id])->find();
        $insert_data['order_id'] = $order_id;
        $insert_data['add_hours'] = $add_hours;
        $insert_data['created_at'] = time();
        $insert_data['originator'] = $this->user_id;
        $insert_data['originator_name'] = $personal_info['name'];
        $insert_data['add_remarks'] = $add_remarks;
        $insert_data['additional_reasons_name'] = $additional_reasons_name;


        db('s_order_append')->insertGetId($insert_data);

        #服务单订单日志
        $data = array();
        $data['order_id'] = $order_id;
        $data['log_msg'] = '服务人员追加服务';
        $data['log_time'] = time();
        $data['log_role'] = 'service';
        $data['log_user'] = $this->user_id;
        $data['log_orderstate'] = 4;

        model('order')->addSorderlog($data);
        return json_success_return([], '操作成功');
    }

    //获取当前用户的最近三条数据
    public function getServiceOrders()
    {
        $parms['som.merid'] = $this->user_id;
        $parms['som.status'] = array('eq', '1');

        $order_list = db('s_order_mechanic')->alias('som')
            ->join('s_order so', 'so.order_id = som.order_id')
            ->where($parms)
            ->order('appointment_unix_time', 'desc')
            ->limit(3)
            ->select();

        $result = [];
        foreach ($order_list as $key => $value) {
            $goods_info = db('s_order_detail')->where('order_id', $value['order_id'])->order('id', 'asc')->find();
            $result[$key]['order_id'] = $value['order_id'];
            $result[$key]['order_type'] = getSorderText($value['order_type']) . ',' . $goods_info['goods_name'];
            $result[$key]['appointment_time'] = date("Y-m-d H:i", $value['appointment_unix_time']);
            $result[$key]['appointment_address'] = $value['appoint_address'];
        }
        json_success_return($result);
    }


    //获取每个状态下订单的数量
    public function getServiceNum()
    {
        $parms['merid'] = $this->user_id;
        $status = intval(input('param.status'));   // 0--待接单 1--已接单 2--已完成
        switch ($status) {
            case 0:
                $parms['status'] = 0;
                break;
            case 1:
                $parms['status'] = 1;
                break;
            case 2:
                $parms['status'] = array('in', '3,4,6');
                break;
            default:
                break;
        }
        $service_count = db('s_order_mechanic')
            ->where($parms)
            ->count();
        json_success_return($service_count);
    }

    //服务端取消订单
    public function getServiceCancel()
    {
        $order_id = intval(input('param.order_id'));
        $user_id = $this->user_id;
        $cancel_reason = input('param.cancel_reason');
        $cancel_remark = input('param.cancel_remark');

        $fuwu_info = db('fuwu_personal')->where(['id' => $user_id])->find();

        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }

        if (empty($cancel_remark)) {
            return json_fail_return('请填写取消说明');
        }

        //判断预约时间前一天可以取消
        $order_info = db('s_order')->where(['order_id' => $order_id])->find();

        if (empty($order_info)) {
            return json_fail_return('暂无可操作订单');
        }

        $appointment_unix_time = $order_info['appointment_unix_time'] - 86400;
        if ($appointment_unix_time < time()) {
            return json_fail_return('距离预约时间不足24小时，不能取消订单，如有特殊情况请联系客服');
        }


        //修改订单状态，修改判断派单表
        db('s_order')->where(['order_id' => $order_id])->update(['order_state' => 7, 'is_mechanic_cancel' => 1]);
        // db('s_order_mechanic')->where(['order_id' => $order_id])->update(['status' => 4]);

        //生成一条记录，由后台审核，审核通过之后，再次由客服派单，一对多，（订单分派表）,还得修改主单状态
        $cancel_data = [
            'order_id' => $order_id,
            'member_id' => $user_id, #操作人
            'mechanic_id' => $user_id, #当前服务人员的id
            'mechanic_name' => $fuwu_info['name'], #当前服务人员的
            'cancel_reason' => $cancel_reason,
            'cancel_remake' => $cancel_remark,
            'c_time' => time(),
            'status' => 0, #0待审核 1审核通过 2审核失败
        ];

        db('s_order_cancel')->insertGetId($cancel_data);

        #服务单订单日志
        $s_data = array();
        $s_data['order_id'] = $order_id;
        $s_data['log_msg'] = '取消订单';
        $s_data['log_time'] = time();
        $s_data['log_role'] = 'buyer';
        $s_data['log_user'] = $user_id;
        $s_data['log_orderstate'] = 1;

        model('order')->addSorderlog($s_data);

        json_success_return([], '取消成功，请等待审核');
    }

    //获取提现费率
    public function getWithdrawalrate()
    {
        $config = db('config')->where('code', 'service_money_radio')->find();
        json_success_return(['rate' => $config['value']], '获取');
    }


    /**
     * Notes:服务端人员提现申请
     * User: shen
     * Date: 2020/4/24
     * Time: 13:57
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function apply_money()
    {

        $user_id = $this->user_id;
        $name = input('param.name', '');
        if (!$name) {
            return json_fail_return('缺少用户名');
        }
        $service_info = db('fuwu_personal')->where('id', $user_id)->find();
        if (!$service_info['name']) {
            return json_fail_return('请先是实名认证');
        }
        if ($service_info['name'] != $name) {
            return json_fail_return('与实名认证的名字不符');
        }

        $card = input('param.card', '');
        if (!$card) {
            return json_fail_return('缺少卡号');
        }
        $card_count = strlen($card);
        /* if ($card_count != 19) {
            return json_fail_return('请输入正确的卡号');
        }*/

        /*if (!is_numeric($card)) {
            return json_fail_return('银行卡号格式错误');
        }*/

        $bank_address = input('param.bank_address', '');
        if (!$bank_address) {
            return json_fail_return('缺少银行开户行地址');
        }

        $bank_name = input('param.bank_name', '');
        if (!$bank_name) {
            return json_fail_return('缺少银行名称');
        }
        $mobile = input('param.mobile', '');
        if (!$mobile) {
            return json_fail_return('缺少联系电话');
        }

        if (is_mobile($mobile) == false) {
            return json_fail_return('手机号格式错误');
        }

        $money = input('param.money', '');
        if (!$money) {
            return json_fail_return('缺少提现金额');
        }

        $radio = input('param.radio', '');
        if (!$radio) {
            return json_fail_return('缺少利率');
        }

        $total_money = input('param.total_money', '');
        if (!$total_money) {
            return json_fail_return('缺少实际可得金额');
        }

        if ($service_info['money'] < $total_money) {
            return json_fail_return('余额不足');
        }

        $content = input('param.content', '');

        $insert_data = [
            'member_id' => $user_id,
            'type' => '1',
            'ctime' => time(),
            'card' => $card,
            'name' => $name,
            'bank_address' => $bank_address,
            'mobile' => $mobile,
            'money' => $money,
            'bank_name' => $bank_name,
            'radio' => $radio,
            'total_money' => $total_money,
            'content' => $content,
        ];

        $res = db('apply_money')->data($insert_data)->insert();
        if (!$res) {
            return json_fail_return('操作失败');
        } else {
            json_success_return([], '请耐心等待审核，审核通过以后5个工作日内到账');
        }
    }

    /**
     * Notes:获取最新一次提现记录
     * User: shen
     * Date: 2020/5/5
     * Time: 12:00
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function new_apply_money_record()
    {
        $member_id = $this->user_id;
        $apply_list = db('apply_money')->where(['member_id' => $member_id, 'type' => 1])->order('id', 'desc')->find();
        json_success_return($apply_list);
    }


    /**
     * Notes:提现记录
     * User: shen
     * Date: 2020/4/24
     * Time: 13:57
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function apply_money_record()
    {
        $member_id = $this->user_id;
        $apply_list = db('apply_money')->where(['member_id' => $member_id, 'type' => 1])->order('id', 'desc')->select();
        json_success_return($apply_list);
    }

    /**
     * Notes:服务人员余额记录
     * User: shen
     * Date: 2020/5/5
     * Time: 17:06
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_money_log()
    {
        $member_id = $this->user_id;
        $type = input('type', '1');
        $page = input('pagenow', '1');
        $limit = input('limit', '10');
        $list = db('money_log')->where(['member_id' => $member_id, 'type' => $type])->page($page, $limit)->order('id', 'desc')->select();
        // foreach ($list as $k => $v) {
        //     $list[$k]['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
        // }
        $count = db('money_log')->where(['member_id' => $member_id, 'type' => $type])->count();
        $return_data = [
            'list' => $list,
            'count' => $count
        ];
        json_success_return($return_data);
    }

    //获取客户端极光imid
    public function getKIm()
    {
        $order_id = intval(input('param.order_id'));
        $order_info = db('s_order')->alias('so')
            ->join('member m', 'm.member_id = so.member_id')
            ->field('so.order_id,m.member_id,so.member_id,m.member_name')
            ->where(['order_id' => $order_id])
            ->find();
        json_success_return(['cliend' => 'kehu' . $order_info['member_name']]);
    }
}
